<!-- GET /api/wifi/networks
返回格式：
[
    {"ssid": "HomeWiFi", "signal": -45},
    {"ssid": "Office", "signal": -60}
]

POST /api/wifi/connect
请求格式：
{
    "ssid": "网络名称",
    "password": "密码"
}
返回格式：
{
    "success": true,
    "newIP": "192.168.1.100",
    "message": "连接成功"
} -->

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备WiFi配置</title>
    <style>
        body {
            font-family: 思源黑体 Medium;
            max-width: 350px;
            margin: 20px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            background: #B2E1E0;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .form-group {
            margin-bottom: 15px;

        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        select, input {
            width: 100%;
            padding: 8px;
            border: 1px solid #dddddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        button {
            background-color: #60a8f5cc;
            color: black;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            width: 100%;
        }

        button:hover {
            background-color: #0056b3;
        }

        #ssid_select button{
            border-radius: 4px;
            margin-top: 0px;
            margin-bottom: 0px;
            padding-top: 15px;
            padding-bottom: 15px;
            padding-left: 30px;
            text-align: left;
            transition: background-color 200ms ease-in-out;
            background-color: #fff;
            color: black;

        }

        #ssid_select button:hover{
            transition: background-color 200ms ease-in-out;
            background-color: #f5f5f5;
            
        }

        #ssid_select .hightlight{
            transition: background-color 200ms ease-in-out;
            background-color: #0fbbeb79;   
        }

        #ssid_select .hightlight:hover{
            transition: background-color 200ms ease-in-out;
            background-color: #0fbbeb79;   
        }

        .hidden{
            display: none;
        }

        .password-input {
            width: 100%;
            padding: 10px;
            padding-right: 40px; /* 为按钮留出空间 */
            box-sizing: border-box;
        }

        .toggle-password {
            position: absolute;
            right: 7px;
            top: 73.5%;
            transform: translateY(-50%);
            cursor: pointer;
            user-select: none;
            color: #666;
            opacity:0.6;
        }

        .toggle-password:hover {
            color: #333;
        }
        
        .status {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }

        .success {
            background-color: #d4edda;
            color: #155724;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
        }

        .loading {
            text-align: center;
            padding: 10px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 style="text-align: center;">WiFi网络配置</h2>
        
        <div class="loading" id="loading">正在扫描可用网络...</div>

        <div class="form-group">
            <p><b>选择网络</b></p>
            <div id="ssid_select" class="form-group" style="background-color: #fff; margin-top: 25px; border-radius: 8px; height: 200px; overflow :hidden auto;">
                <button id="no_wifi_ap"><span style="display: block; text-align: center;">附近无可用的WIFI热点</span></button>
                <!-- <button>SSID1</button>
                <button>SSID2</button>
                <button>SSID3</button>
                <button>SSID4</button>
                <button>SSID5</button>
                <button>SSID6</button>
                <button>SSID7</button>
                <button>SSID8</button>
                <button>SSID9</button>
                <button>SSID10</button>
                <button>SSID11</button>
                <button>SSID12</button> -->

            </div>        
            <button onclick="refreshNetworks()" style="margin-top:10px; background:#74E2CC; color:black">刷新网络列表</button>
        </div>

        <div class="form-group" style="margin-top: 40px; position: relative;">
            <label for="password">WiFi密码</label>
            <input type="password" data="passworedtype" id="password"  style="margin-top: 15px;border-radius: 6px; height: 40px;font-size: 14px;" placeholder="输入WiFi密码">
            <span class="toggle-password" id="togglePassword">👁️</span>
        </div>

        <button onclick="connectWiFi()">连接网络</button>

        <div id="statusMessage" class="status"></div>
    </div>

    <script>   
        var SSID=null;
        const setSSID=document.getElementById('ssid_select');


        //页面加载时自动获取网络列表
        window.onload = function() {
            refreshNetworks();
        }

        // 选中SSID后高亮按钮
        setSSID.addEventListener('click',(event)=>{
            const isButton = event.target.nodeName === 'BUTTON';
            var no_wifi_ap=false;
            if (!isButton) {return;}

            //取消其他按钮的高亮，高亮选中的按钮,顺便检查是不是本来就没有AP可用
            Array.from(setSSID.children).forEach(i => {
                i.classList.remove('hightlight');
                
                if((!i.classList.contains('hidden'))&&i.id==="no_wifi_ap")no_wifi_ap=true;
            });
            //如果没有热点可用，直接返回
            if(no_wifi_ap){no_wifi_ap=false;return;}

            //高亮选中的按钮
            event.target.className='hightlight';

            //记录选中的SSID
            SSID=event.target.id.slice(5);
            //SSID=event.target.textContent;
            console.info("设置要连接的ssid为\""+SSID+"\"");
        })

        //获取选中的SSID名称
        function GetSSID()
        {
            return SSID;
        }

        //切换密码输入框可见性
        const togglePassword = document.querySelector('#togglePassword');
        const passwordInput = document.querySelector('#password');

        togglePassword.addEventListener('click', function() {
            // 切换输入框类型
            const type = passwordInput.getAttribute('type') === 'password' 
                        ? 'text' 
                        : 'password';
            passwordInput.setAttribute('type', type);
            
            // 切换按钮样式
            this.style.opacity = type === 'password' ? '0.6' : '1';
        });

        var abc;
        // 获取可用网络列表
        async function refreshNetworks() {
            
            showLoading(true);
            try {
                const response= await fetch('/api/wifi/networks.json');
                const networks= await response.json();

                if(networks.status===-1)
                {
                    clearTimeout(abc);
                    abc=setTimeout(refreshNetworks(), 1000);
                    return;
                }
                else if(networks.status>=0){
                    clearTimeout(abc);
                }
                else
                {
                    我要抛出错误了=错误;
                }

                Array.from(setSSID.children).forEach(i => {
                    if(i.id!=="no_wifi_ap"){
                        setSSID.removeChild(i);
                    };
                });
                
                console.log("找到"+networks.ap.length+"个WIFI热点");
                const no_wifi_ap = document.getElementById('no_wifi_ap');
                if(networks.ap.length===0){
                    no_wifi_ap.classList.remove('hidden')
                    return;
                }
                else
                {
                    no_wifi_ap.classList.add('hidden')
                }
                

                networks.ap.forEach(network => {
                    const button = document.createElement('button');
                    button.textContent = `${network.ssid} (${network.signal}dBm)`;
                    setSSID.appendChild(button);
                    button.id="ssid_"+network.ssid;
                });

            } catch (error) {
                showMessage('无法获取网络列表，请重试', 'error');
            } finally {
                showLoading(false);
            }
        }

        // 连接WiFi
        async function connectWiFi() {
            const ssid =GetSSID();
            console.log(ssid);
            const password = document.getElementById('password').value;

            if (!ssid) {
                showMessage('请先选择要连接的网络', 'error');
                return;
            }
            if(password.length<=7)
            {
                showMessage('请输入8位以上的密码', 'error');
                return;
            }

            try {
                const response = await fetch('/api/wifi/connect', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ssid: ssid,
                        password: password
                    })
                });

                const result = await response.json();
                if (result.success) {
                    showMessage('连接成功！本设备ip为：'+result.newIP, 'success');
                    // 3秒后尝试跳转
                } else {
                    showMessage(`连接失败: ${result.message}`, 'error');
                }
            } catch (error) {
                showMessage('网络请求失败，请检查连接', 'error');
            }
        }

        function showMessage(message, type) {
            const statusDiv = document.getElementById('statusMessage');
            statusDiv.className = `status ${type}`;
            statusDiv.textContent = message;
            statusDiv.style.display = 'block';
        }

        function showLoading(show) {
            document.getElementById('loading').style.display = show ? 'block' : 'none';
        }
    </script>
</body>
</html>